<?php
/**
 * PostController.php
 *
 * @category    Madoqua
 * @package     Module
 * @subpackage  BlogAdmin
 */

/** base clas */
require_once 'Madoqua/Controller/Action/Abstract.php';

/** action cacher */
require_once 'Madoqua/Cache/Action.php';

/**
 * BlogAdmin_PostController
 *
 * managing posts
 *
 * @category    Madoqua
 * @package     Module
 * @subpackage  BlogAdmin
 */

class BlogAdmin_PostController extends Madoqua_Controller_Action_Abstract
{
    /**
     * Post model
     *
     * @var Blog_Post
     */
    private $_postModel;

    /**
     * Comments model
     *
     * @var Blog_Comment
     */
    private $_commentModel;

    /**
     * Category model
     *
     * @var Blog_Category
     */
    private $_categoryModel;

    /**
     * PostCategory model
     *
     * @var Blog_PostCategory
     */
    private $_postCategoryModel;

    /**
     * initialization
     */
    public function init() {
        parent::init();

        $this->_modelLoader->load(array('Blog_Post', 'Blog_Comment', 'Blog_Category', 'Blog_PostCategory'));
        $this->_postModel = new Blog_Post();
        $this->_commentModel = new Blog_Comment();
        $this->_categoryModel = new Blog_Category();
        $this->_postCategoryModel = new Blog_PostCategory();
        //set up model(s)

        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajah = array('search', 'update', 'create', 'table');
        foreach($ajah as $action) {
            $ajaxContext->addActionContext($action, 'html');
        }
        $ajaxContext->initContext();
        //set up the content helper for certain actions
    }

    /**
     * index
     */
    public function indexAction()
    {
        $form = $this->_formLoader->get('BlogAdmin_Post_Search');
        $this->view->searchForm = $form;
    }

    /**
     * search for a post
     *
     * @todo move search logic to model layer
     */
    public function searchAction() {
        $form = $this->_formLoader->get();
        $this->view->form = $form;

        $q = $this->getRequest()->getQuery('q');
        $this->view->query = $q;

        if (!empty($q) && $form->isValid($this->getRequest()->getQuery())) {
            $this->view->results = Blog_Post::search($q);
            //and let's search!
        }
    }

    /**
     * recent posts
     */
    public function recentAction() {
        $count = (int) $this->_getParam('count', 10);
        $posts = $this->_postModel->fetchAll(null, 'posted DESC', $count);
        $this->view->posts = $posts;
    }

    /**
     * list posts
     */
    public function listAction()
    {
    }
    
    /**
     * a nice table of posts
     */
    public function tableAction()
    {
        $count = (int) $this->_getParam('count', 10);
        //count
        
        $sort = strtolower(trim($this->getRequest()->getParam('sort', 'posted')));
        if (!in_array($sort, $this->_postModel->info('cols'))) {
            throw new Exception($sort . ' is not a column');
        }
        //column
        
        $dir = strtoupper(trim($this->getRequest()->getParam('dir', 'DESC')));
        if (!in_array($dir, array('DESC', 'ASC'))) {
            throw new Exception($dir . ' is not a valid sort direction');
        }
        //sort dir
        
        $posts = $this->_postModel->fetchAll(null, $sort . ' ' . $dir, $count);
        $this->view->posts = $posts;
        $this->view->sort = $sort;
        $this->view->dir = strtolower($dir);
    }

    /**
     * gimme a C! (You know... crud :x)
     */
    public function createAction()
    {
        $form = $this->_formLoader->get('BlogAdmin_Post_Post');
        $this->view->form = $form;

        if ($form->isPrg() && $form->isValid($form->getPrgData())) {
            $form->populate($form->getPrgData());
            $post = $this->_postModel->fetchNew();
            //the new post
            $post->posted = time();
            //set time to right now (because we're posting it... now!)
            
            $this->save($post, $form);
            //save it
            
            $this->getHelper('redirector')->gotoRoute(
                array(
                        'controller' => 'post', 
                        'action' => 'update',
                        'id' => $post->id
                ),
                'blog_admin'
                );
        }
    }

    /**
     * making it all better
     */
    public function updateAction()
    {
        $id = (int) $this->_getParam('id', 0);
        $post = $this->_postModel->find($id)->current();
        if ($post == null) {
            throw new Exception('Post not found');
        }

        $form = $this->_formLoader->get('BlogAdmin_Post_Post');
        $this->view->form = $form;
        //theform
        
        $form->populateFromPost($post);
        //populate
        
        $this->view->id = $id;
        //ID needed for deletion

        if ($form->isPrg() && $form->isValid($form->getPrgData())) {
            $this->save($post, $form);
            $this->view->success = true;
            //remember success!
        }
    }

    /**
     * perform the save
     *
     * @param Blog_Post_Row $post
     * @param Madoqua_Form $form
     */
    private function save($post, $form) {
        $post->setFromArray($form->getModelValues($this->_postModel));
        //set the values
        $this->checkSlug($post);
        //check the slug
        $post->save();
        //save it

        $categories = $form->getValues();
        $categories = $categories['categories']['category'];
        $this->_postCategoryModel->updatePost($post, $categories);
        //update categories

        $this->updateCache();
        //update the action cache

        $form->cleanPrgData();
        //remove prg data
    }

    /**
     * Delete a post
     */
    public function deleteAction()
    {
        //XSS check
        if(empty($_POST)) {
            throw new Exception('Post data must be present in in order to delete a post.');
        }
        
        $id = $this->_request->getParam('id');
        
        if(!$id) {
	        throw new Exception('No post ID specified for deletion');
	    }
	    
	    $this->_postModel->deleteById($id);
	    $this->_commentModel->deleteByPostId($id);
	    $this->updateCache();
        
	    //Send to user back to the admin home page
        $this->_helper->viewRenderer->setNoRender(true);
        $this->_helper->layout()->disableLayout();
        
        $redirector = $this->_helper->getHelper('Redirector');
        $redirector->setGoToSimple('index', 'post', 'admin');
    }
    
    /**
     * Confirm deletion of a post
     */
	public function deleteConfirmAction() {
        $id = $this->_request->getParam('id');
        if (!$id) {
            throw new Exception('No post ID specified for deletion');
        }
        
        //Get the post details so we 
        $post = $this->_postModel->fetchById($id);
        
        if(!$post) {
            throw new Exception('The specified post ID could not be found');
        }
        
        $this->view->post = $post;
	}

    /**
     * check and set slug
     *
     * @param Zend_Db_Table_Row $post
     */
    private function checkSlug($post) {
        if (strlen($post->slug) < 3) {
            $post->slug = Blog_Post::slugify($post->title, true);
        }
    }

    /**
     * update the action cache
     */
    private function updateCache() {
        $cache = Madoqua_Cache_Action::get();
        //get the action cacher
        $cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array(
            'controller_post' 
            ));
            //clear all post controller caches
    }

}
